import http from 'http'
import { Server } from 'socket.io'

const server = http.createServer()

const io = new Server(server, {
  cors: true,
})
const groupMap = {}
// 事件模型驱动
io.on('connection', (socket) => {
  // 加入房间
  socket.on('join',({name,room}) => {
    // 创建一个房间
    socket.join(room)
    if (groupMap[room]) {
      groupMap[room].push({name,room,id: socket.id})
    } else {
      groupMap[room] = [{name,room,id: socket.id}]
    }
    socket.emit('groupMap',groupMap)
    // 向所有人通知
    socket.broadcast.emit('groupMap',groupMap)
    // 管理员消息
    socket.broadcast.to(room).emit('message',{
      name: '管理员',
      message: `欢迎${name}加入${room}房间`
    })
  })
  socket.on('message',({name,message,room}) => {
    socket.broadcast.to(room).emit('message',{
      name,
      message
    })
  })
})

server.listen(3000, () => {
  console.log('Server is running on port 3000');
})